/**   
 * @Title: HomeAct.java 
 * @Package com.esun.cheetah.view.match
 * @Description: 主界面跳转控制
 * @author 程相亭 <br/>
 * @date 2012-03-13 下午05:07:33  
 * Copyright (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.cheetah.view;

import android.app.ActivityGroup;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.esun.cheetah.R;
import com.esun.cheetah.biz.personal.attention.LoginOutComm;
import com.esun.cheetah.biz.setting.CheckUpgradeCommunicater;
import com.esun.cheetah.biz.setting.CheckUpgradeCommunicater.UpgradeInfo;
import com.esun.cheetah.common.IActivityResult;
import com.esun.cheetah.config.Config;
import com.esun.cheetah.config.Language;
import com.esun.cheetah.view.custom.UpgradeDialog;
import com.esun.cheetah.view.match.matchlist.ScoreActivity;
import com.esun.cheetah.view.news.NewsAct;
import com.esun.cheetah.view.odds.activity.OddsAgp;
import com.esun.cheetah.view.personal.LoggedinAct;
import com.esun.cheetah.view.personal.PersonalAct;
import com.esun.cheetah.view.setting.AboutAct;
import com.esun.cheetah.view.setting.ChooseLanguageAct;
import com.esun.cheetah.view.setting.ChooseProTime;
import com.esun.cheetah.view.setting.ChooseSuggest;
import com.esun.cheetah.view.setting.HelpAct;
import com.esun.cheetah.view.setting.SetDetailsAct;
import com.esun.cheetah.view.setting.service.NotificationService;
import com.esun.util.VersionUtils;
import com.esun.util.log.EDebug;

/**
 * @ClassName: HomeAct
 * @Description:主界面
 * @author 程相亭 <br/>
 * @date 2012-03-13 下午05:07:33
 */
public class HomeAct extends ActivityGroup implements OnCheckedChangeListener, OnClickListener, IActivityResult {

	// 容器view
	private LinearLayout bodyView;
	private RadioGroup rgFooter;

	private RadioButton rbMatch;
	private RadioButton rbPeilv;
	private RadioButton buyLottery;
	private RadioButton rbAcount;
	private RadioButton moreRbt;
	private View moreView;
	private ImageView imNews;
	private ImageView imAccountProctect;
	private ImageView imChooseLanguage;
	private ImageView imHelp;
	private ImageView imPromp;
	private ImageView imUpdate;
	private ImageView imUserSuggest;
	private ImageView imAboutUs;
	private LinearLayout llytNews;
	private LinearLayout llytAccount;
	private LinearLayout llytChooseLanguage;
	private LinearLayout llytHelp;
	private LinearLayout llytPromp;
	private LinearLayout llytUpdate;
	private LinearLayout llytSuggest;
	private LinearLayout llytAboutUs;

	// 通过标记跳转不同的页面，显示不同的菜单项
	public static int flag = 0;

	private Dialog quitDialog;
	private Button btnDialogSubmit;
	private Button btnDialogcancel;
	private TextView tvDialogMsg;

	public static boolean isActive = false; // 客户端是否启动
	private LinearLayout buttomLlyt;
	/** 更多动画 */
	private ViewFlipper viewfipper;
	/** 更多弹出popupWindow */
	private PopupWindow popup;

	/** 注销handler */
	Handler loginOutHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Config.COMMUNICATER_SUCCESS:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		isActive = true;

		initMainView();
		footerShow();
		showView(flag);
		
		if (VersionUtils.getInstance().needUpgrade()) {
			showUpgradDialog(VersionUtils.getInstance().getUpgradeInfo());
			VersionUtils.getInstance().setNeedUpgrade(false);
		}
		showPromotionDialog();	
	}

	/**
	 * @title showUpgradDialog
	 * @description 显示下载的对话框
	 * @param info
	 */
	protected void showUpgradDialog(final UpgradeInfo info) {
		final UpgradeDialog dialog = new UpgradeDialog(this);
		dialog.setCancelable(false);
		dialog.setMessage(Html.fromHtml(info.upgradeDescription));
		dialog.setOnLeftButtonClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// added by kuroky 强制更新
				if (VersionUtils.getInstance().ismMustUpgrade()) {
					dialog.dismiss();
					android.os.Process.killProcess(android.os.Process.myPid());
				} else {
					dialog.dismiss();
				}
			}
		});
		dialog.setOnRightButtonClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
				Intent downloadIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(info.url));
				startActivity(downloadIntent);
			}
		});
		dialog.show();
	}

	/**
	 * @param popup
	 * @Title: initMainView
	 * @Description: view初始化
	 * @param
	 * @return
	 * @throws
	 */
	public void initMainView() {
		
		bodyView = (LinearLayout) findViewById(R.id.ll_matchhome_act);
		rgFooter = (RadioGroup) findViewById(R.id.rg_cheetah_footer);
		rgFooter.setOnCheckedChangeListener(this);
		rbMatch = (RadioButton) findViewById(R.id.rb_match);
		rbPeilv = (RadioButton) findViewById(R.id.rbPeilv);
		buyLottery = (RadioButton) findViewById(R.id.rbBuyLottery);
		rbAcount = (RadioButton) findViewById(R.id.rbAccount);
		moreRbt = (RadioButton) findViewById(R.id.moreRbt);
		moreRbt.setOnClickListener(new ShowClickListener());
		buttomLlyt = (LinearLayout) findViewById(R.id.bottomLyyt);
		viewfipper = createViewFilpper();
		popup = createPopupWindow();
	}

	public void footerShow() {
		switch (flag) {
		case 0:
			rbMatch.setChecked(true);
			break;
		case 1:
			rbPeilv.setChecked(true);
			break;
		case 2:
			buyLottery.setChecked(true);
			break;
		case 3:
			rbAcount.setChecked(true);
			break;
		default:
			break;
		}
	}

	/**
	 * @Title: showView
	 * @Description: 控制加载不同的页面
	 * @param flag
	 * @return
	 * @throws
	 */
	public void showView(int flag) {
		bodyView.removeAllViews();
		switch (flag) {
		case 0:
			// 加载比赛列表页面

			View viewMatch = getLocalActivityManager().startActivity("match", new Intent(HomeAct.this, ScoreActivity.class)).getDecorView();
			bodyView.addView(viewMatch, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			break;

		case 1:
			// 加载赔率界面
			// bodyView.removeAllViews();
			// View viewPersonal =
			// getLocalActivityManager().startActivity("personal", new
			// Intent(HomeAct.this, MatchListActivity.class))
			// .getDecorView();
			//
			// bodyView.addView(viewPersonal, LayoutParams.FILL_PARENT,
			// LayoutParams.FILL_PARENT);
			bodyView.removeAllViews();
			Intent intentPeilv = new Intent();
			intentPeilv.setClass(HomeAct.this, OddsAgp.class);
			Bundle bundlePeilv = new Bundle();
			bundlePeilv.putInt("CURRENT_TAB_NUM", 0);
			intentPeilv.putExtras(bundlePeilv);
			EDebug.o(this, "click to shuangseqiu choose");
			// startActivity(intentToSportteryFootball);
			View viewPeilv = getLocalActivityManager().startActivity("peilv", intentPeilv).getDecorView();

			bodyView.addView(viewPeilv, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			break;

		case 2:
			// 加载购彩界面
			// bodyView.removeAllViews();
			// View viewNews = getLocalActivityManager().startActivity("news",
			// new Intent(HomeAct.this, PersonalAct.class)).getDecorView();
			//
			// bodyView.addView(viewNews, LayoutParams.FILL_PARENT,
			// LayoutParams.FILL_PARENT);
			bodyView.removeAllViews();
			Intent intentToSportteryFootball = new Intent();
			intentToSportteryFootball
					.setClass(HomeAct.this, com.esun.cheetah.view.personal.sportlotteryfootball.SportteryFootballAgp.class);
			Bundle bundleToSportteryFootbal = new Bundle();
			bundleToSportteryFootbal.putInt("CURRENT_TAB_NUM", 0);
			intentToSportteryFootball.putExtras(bundleToSportteryFootbal);
			intentToSportteryFootball.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			EDebug.o(this, "click to shuangseqiu choose");
			// startActivity(intentToSportteryFootball);
			View viewBuyLotter = getLocalActivityManager().startActivity("peilv", intentToSportteryFootball).getDecorView();

			bodyView.addView(viewBuyLotter, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			break;

		case 3:
			// 加载账户
			View viewSetting = getLocalActivityManager().startActivity("personal", new Intent(HomeAct.this, PersonalAct.class))
					.getDecorView();

			bodyView.addView(viewSetting, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			break;
		case 4:
			// 加载登录后
			View viewLogined = getLocalActivityManager().startActivity("setting", new Intent(HomeAct.this, LoggedinAct.class))
					.getDecorView();
			bodyView.addView(viewLogined, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			break;
		default:
			break;
		}
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {

		switch (checkedId) {

		// 比赛点击事件
		case R.id.rb_match:
			flag = 0;

			break;

		// 赔率
		case R.id.rbPeilv:
			flag = 1;

			break;

		// 购彩
		case R.id.rbBuyLottery:
			flag = 2;

			break;

		// 账户
		case R.id.rbAccount:
			flag = 3;

			break;

		default:
			break;
		}

		showView(flag);

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 这里放捕获按键处理事件
			showQuitDialog();
			return true;
		} else
			return super.onKeyDown(keyCode, event);
		// 除了捕获你想要的返回键之外，其余的应该交给他的父类去处理
	}

	private void showQuitDialog() {
		quitDialog = new Dialog(this, R.style.dialog);
		quitDialog.getWindow().setContentView(R.layout.dialog_quit);

		tvDialogMsg = (TextView) quitDialog.getWindow().findViewById(R.id.tvPleaseInputPassword);
		tvDialogMsg.setText(Language.MSG_QUITDIALOG);
		btnDialogcancel = (Button) quitDialog.getWindow().findViewById(R.id.btCancel);
		btnDialogcancel.setOnClickListener(HomeAct.this);
		btnDialogSubmit = (Button) quitDialog.getWindow().findViewById(R.id.btSure);
		btnDialogSubmit.setOnClickListener(this);

		quitDialog.show();
	}

	@Override
	public void onClick(View v) {
		onItemChance(v.getId());
		switch (v.getId()) {
		case R.id.btSure:

			// 退出前通信
			new LoginOutComm(loginOutHandler).startCommunicate();
			Intent i = new Intent();
			i.setClass(HomeAct.this, NotificationService.class);
			stopService(i);
			android.os.Process.killProcess(android.os.Process.myPid());
			break;

		case R.id.btCancel:
			quitDialog.dismiss();
			break;
		default:

			break;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		((IActivityResult) this.getCurrentActivity()).onResult(requestCode, resultCode, data);
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onResult(int requestCode, int resultCode, Intent data) {

	}

	/**
	 * 更多弹出的方向
	 * 
	 * @return ViewFlipper
	 */

	private ViewFlipper createViewFilpper() {
		ViewFlipper viewfipper = new ViewFlipper(this);
		viewfipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.more_in));
		viewfipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.more_out));
		viewfipper.setFlipInterval(6000000);
		return viewfipper;
	}

	/**
	 * 弹出popupWindow
	 * 
	 * @return
	 */

	private PopupWindow createPopupWindow() {
		PopupWindow popup = new PopupWindow(viewfipper, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		popup.setFocusable(true);
		popup.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_default_more_480x223));
		popup.update();
		return popup;
	}

	/**
	 * 点击 弹出 popupWindow 的弹出或者关闭事件
	 * 
	 * @author renfj
	 * 
	 */
	class ShowClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			if (popup != null) {
				if (popup.isShowing()) {
					popup.dismiss();
				} else {
					popup.showAtLocation(buttomLlyt, Gravity.BOTTOM, 0, buttomLlyt.getHeight() + 10);
					popup.showAtLocation(buttomLlyt, Gravity.BOTTOM, 0, buttomLlyt.getHeight() + 10);
					viewfipper.startFlipping();
					initMoreView();
				}
			}

		}


	}

	/**
	 * 更多每一项的 跳转
	 * 
	 * @param id
	 */
	private void onItemChance(int id) {
		Intent mIntent = new Intent();
		switch (id) {
		case R.id.llytNews:
		case R.id.imNew:
			mIntent.setClass(HomeAct.this, NewsAct.class);
			startActivity(mIntent);
			popup.dismiss();
			break;
		case R.id.llytAccount:
		case R.id.imAccountProctect:
			mIntent.setClass(HomeAct.this, ChooseProTime.class);
			startActivity(mIntent);
			popup.dismiss();
			break;
		case R.id.llytChooseLanguage:
		case R.id.imChooseLanguage:
			mIntent.setClass(HomeAct.this, ChooseLanguageAct.class);
			startActivity(mIntent);
			finish();
			break;
		case R.id.llytHelp:
		case R.id.imHelp:
			mIntent.setClass(HomeAct.this, HelpAct.class);
			startActivity(mIntent);
			popup.dismiss();
			break;
		case R.id.imPromp:
		case R.id.llytPromp:
			mIntent.setClass(HomeAct.this, SetDetailsAct.class);
			startActivity(mIntent);
			popup.dismiss();
			break;
		case R.id.llytUpdate:
		case R.id.imUpdate:
			popup.dismiss();
			checkUpgrade();
			break;
		case R.id.imUserSuggest:
		case R.id.llytSuggest:
			mIntent.setClass(HomeAct.this, ChooseSuggest.class);
			startActivity(mIntent);
			popup.dismiss();
			break;
		case R.id.imAboutUs:
		case R.id.llytAboutUs:
			mIntent.setClass(HomeAct.this, AboutAct.class);
			startActivity(mIntent);
			popup.dismiss();
			break;
		default:
			break;
		}
	}

	/**
	 * @title checkUpgrade
	 * @description 检查更新
	 */
	private void checkUpgrade() {
		Toast.makeText(HomeAct.this, "正在检测新版本...", Toast.LENGTH_LONG).show();
		Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				if (msg.what == Config.COMMUNICATER_SUCCESS) {
					VersionUtils.getInstance().setActived(HomeAct.this);
					UpgradeInfo info = (UpgradeInfo) msg.obj;
					if (info.isUpgrade) {
						showUpgradeDialog(info);
					} else {
						showNotNeedUpgrade();
					}
				} else {
					Toast.makeText(getParent(), "检测失败！", Toast.LENGTH_SHORT).show();
				}
			}

		};
		final String channel = VersionUtils.getInstance().getChannel(this);
		final int version = VersionUtils.getInstance().getVersion(this);
		final int isJiHuo = VersionUtils.getInstance().getIsActive(this);
		final String sysVersion = Build.VERSION.RELEASE;
		final String screenreso = VersionUtils.getInstance().getScreenreso(this);
		final String serial = VersionUtils.getInstance().getSerial(this);
		if (TextUtils.isEmpty(channel) || version < 0) {
			return;
		}
		CheckUpgradeCommunicater mCheckUpgradeCommunicater = new CheckUpgradeCommunicater(handler, this, version, channel, sysVersion,
				screenreso, serial, isJiHuo);
		mCheckUpgradeCommunicater.startCommunicate();
	}

	/**
	 * @title showUpgradDialog
	 * @description 显示下载的对话框
	 * @param info
	 */
	protected void showUpgradeDialog(final UpgradeInfo info) {
		final UpgradeDialog dialog = new UpgradeDialog(this);
		dialog.setMessage(Html.fromHtml(info.upgradeDescription));
		dialog.setOnLeftButtonClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.setOnRightButtonClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
				Intent downloadIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(info.url));
				startActivity(downloadIntent);
			}
		});
		dialog.show();
	}

	/**
	 * @title showNotNeedUpgrade
	 * @description
	 */
	protected void showNotNeedUpgrade() {

		final Dialog showVersionUpdate = new Dialog(this, R.style.dialog);
		showVersionUpdate.getWindow().setContentView(R.layout.version_update);
		showVersionUpdate.show();
		Button btnSure = (Button) showVersionUpdate.findViewById(R.id.btUserSure);
		btnSure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showVersionUpdate.cancel();

			}
		});
	}
	/**
	 * 实例化更多弹出界面
	 */
	private void initMoreView() {
		moreView=getLayoutInflater().inflate(R.layout.more, null);
		viewfipper.addView(moreView);
		imNews=(ImageView) moreView.findViewById(R.id.imNew);
		llytNews=(LinearLayout) moreView.findViewById(R.id.llytNews);
		llytAccount=(LinearLayout) moreView.findViewById(R.id.llytAccount);
		llytChooseLanguage=(LinearLayout) moreView.findViewById(R.id.llytChooseLanguage);
		llytHelp=(LinearLayout) moreView.findViewById(R.id.llytHelp);
		llytPromp=(LinearLayout) moreView.findViewById(R.id.llytPromp);
		llytUpdate=(LinearLayout) moreView.findViewById(R.id.llytUpdate);
		llytSuggest=(LinearLayout) moreView.findViewById(R.id.llytSuggest);
		llytAboutUs=(LinearLayout) moreView.findViewById(R.id.llytAboutUs);
		imAccountProctect=(ImageView) moreView.findViewById(R.id.imAccountProctect);
		imChooseLanguage=(ImageView) moreView.findViewById(R.id.imChooseLanguage);
		imHelp=(ImageView) moreView.findViewById(R.id.imHelp);
		imPromp=(ImageView) moreView.findViewById(R.id.imPromp);
		imUpdate=(ImageView) moreView.findViewById(R.id.imUpdate);
		imUserSuggest=(ImageView) moreView.findViewById(R.id.imUserSuggest);
		imAboutUs=(ImageView) moreView.findViewById(R.id.imAboutUs);
		llytAboutUs.setOnClickListener(this);
		llytSuggest.setOnClickListener(this);
		llytUpdate.setOnClickListener(this);
		llytPromp.setOnClickListener(this);
		llytHelp.setOnClickListener(this);
		llytChooseLanguage.setOnClickListener(this);
		llytAccount.setOnClickListener(this);
		imAboutUs.setOnClickListener(this);
		llytNews.setOnClickListener(this);
		imUserSuggest.setOnClickListener(this);
		imUpdate.setOnClickListener(this);
		imPromp.setOnClickListener(this);
		imHelp.setOnClickListener(this);
		imChooseLanguage.setOnClickListener(this);
		imNews.setOnClickListener(this);
		imAccountProctect.setOnClickListener(this);
	}
	/**
	 * 活动对话框
//	 */
	private void showPromotionDialog() {
		final Dialog promotionDialog=new Dialog(this,R.style.dialog);
		promotionDialog.setContentView(R.layout.promotion_promp);
		promotionDialog.show();
		Button btnSure=(Button) promotionDialog.findViewById(R.id.btUserSure);
		btnSure.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				promotionDialog.dismiss();
//				Intent mIntent=new Intent(HomeAct.this, HuoDAct.class);
//				startActivity(mIntent);
			}
		});
		Button btnCancel=(Button) promotionDialog.findViewById(R.id.btUserCancel);
		btnCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				promotionDialog.dismiss();
				
			}
		});
	}

}
